<?php
/**
 * ooPHP - object oriented PHP framework
 * @author Kamil Mikolajczyk ( rego (at) gazeta (dot) pl )
 * @version 1.0
 *
 */

/**
 * MySQL Database Manager
 * @author Kamil Mikolajczyk ( rego (at) gazeta (dot) pl )
 * @version 1.0
 *
 */
 class DBManager{
  
	/**
	 * Connection
	 * @var SQLConnection
	 */
 	var $link = null;
	
	/**
	 * Is connected?
	 * @var boolean
	 */
 	var $connected = false;
	
	/**
	 * Result set
	 * SQLResultSet
	 */
 	var $rs = null;
 	
	/**
	 * Constructor
	 * Connects with server with given data
	 * @param $url server's address
	 * @param $user username
	 * @pass $pass password
	 * @optional $dbName database's name
	 */
 	function DBManager($url, $user, $pass, $dbName = null)
 	{
 		$this -> link = mysql_connect($url, $user, $pass) or die('Could not connect: ' . mysql_error());
 		if($dbName){
			$this -> connected = mysql_select_db($dbName,$this -> link) or die ('Could not connect: ' . mysql_error());
 		}
 	}
 	
	/**
	 * Connects to database of given name
	 * @param $dbName database's name
	 */
 	function connectToDB($dbName)
 	{
 		if($this -> link)
		{
 			$this -> connected = mysql_select_db($dbName,$this -> link) or die ('Could not connect: ' . mysql_error());
		}
		else
			throw new Exception('DBManager::connectToDB() - not connected');
		$this -> connected = true;
 	}
 	
	/**
	 * Executes query and saves results in result set $this->rs
	 * @param $query query
	 */
 	function executeQuery($query)
 	{
 		if($this -> link && $this -> connected)
 		{
 			$this -> rs = null;
 			$this -> rs = mysql_query($query);
 		}
		else
			throw new Exception('DBManager::executeQuery() - not connected');
 	}
 	
	/**
	 * Fetches all rows form result set
	 * @optional $rs result set, by default it's $this -> rs
	 * @return array of rows
	 */
 	function fetchAll($rs = null)
 	{
 		$result = Array();
		if(!$rs)
			$rs = $this -> rs;
 		if($rs)
 		{
	 		while($row = mysql_fetch_array($rs, MYSQL_BOTH))
	 		{
	 			$result[] = $row;
	 		}
 		}
		else
			throw new Exception('DBManager::fetchAll() - missing resultSet');
 		return $result;
 	}
	
	/**
	 * Fetches given count of rows form result set
	 * @optional $howMany row count, by default it's 1
	 * @optional $rs result set, by default it's $this -> rs
	 * @return array of rows
	 */
 	function fetch($howMany = 1, $rs = null)
 	{
 		$result = Array();
		if(!$rs)
			$rs = $this -> rs;
 		if($rs)
 		{
	 		while($row = mysql_fetch_array($rs, MYSQL_BOTH))
	 		{
				if($howMany--<1)
					break;
	 			$result[] = $row;
	 		}
 		}
		else
			throw new Exception('DBManager::fetch() - missing resultSet');
 		return $result; 		
 	}
 	
 	
 }
 ?>